package com.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;


import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bean.Complex;
import com.bean.Openingreport;
import com.bean.Openingreporthouseparticular;
import com.bean.Project;
import com.bean.Room;
import com.service.ComplexService;
import com.service.OpeninghouseService;
import com.service.OpeningreportService;
import com.service.ProjectService;
import com.service.RoomService;
import com.util.Export;



@Controller
@RequestMapping("openingreport")
public class OpeningreportAction {
	
	
	@Autowired
	private ProjectService projectservice;
	@Autowired
	private OpeningreportService openingreportservice;
	@Autowired
	private OpeninghouseService ophservice;
	@Autowired
	private ComplexService complexservice;
	@Autowired
	private RoomService roomservice;
	
	
	
	@RequestMapping("toList")
    public String toList(Model model){
		
		List<Openingreport> list = openingreportservice.select();
		model.addAttribute("list", list);
		return "openingreport/list";
    }
	@RequestMapping("toList1")
    public String toList1(String name,String state,Model model){
		
		Map<String, Object> map = new HashMap<String,Object>();
		if(name != null && "".equals(name.trim())){
			name = null;
		}
		if(state != null && "".equals(state.trim())){
			state = null;
		}
		map.put("name", name);
		map.put("state", state);
		List<Openingreport> list = openingreportservice.selectBy(map);
		model.addAttribute("list", list);
		return "openingreport/list";
    }
	@RequestMapping("toShenhe")
    public String toShenhe(String name,String state,Model model) throws UnsupportedEncodingException{
		List<Project> projects = projectservice.select(null);
		Map<String, Object> map = new HashMap<String,Object>();
		if(name != null && "".equals(name.trim())){
			name = null;
		}
		if(state != null && "".equals(state.trim())){
			state = null;
		}
		System.out.println(state);
		String state1 = new String(state.getBytes("ISO8859-1"),"UTF-8");
		System.out.println(state1);
		map.put("state", state1);
		map.put("name", name);
		List<Openingreport> list = openingreportservice.selectBy(map);
		model.addAttribute("list", list);
		model.addAttribute("projects", projects);
		return "openingreport/shenhe";
    }
	@RequestMapping("toShenhe1")
    public String toShenhe1(Model model){
		List<Project> projects = projectservice.select(null);
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("state", "未审核");
		List<Openingreport> list = openingreportservice.selectBy(map);
		model.addAttribute("list", list);
		model.addAttribute("projects", projects);
		return "openingreport/shenhe";
    }
	
	@RequestMapping("toAdd")
    public String toAdd(String name,Model model,HttpServletRequest request){
		request.getSession().setAttribute("ophs", null);
		request.getSession().setAttribute("rooms", null);
		List<Openingreporthouseparticular> ophs = new ArrayList<Openingreporthouseparticular>();
		request.getSession().setAttribute("ophs", ophs);
		
		
		Map<String, Object> map = new HashMap<String,Object>();
		if(name != null && "".equals(name.trim())){
			name = null;
		}
		map.put("name", name);
		List<Project> list=projectservice.select(map);
		model.addAttribute("list", list);
		return "openingreport/add";
    }
	
	@RequestMapping("add2")
    public String add2(Openingreport op,Integer num, Model model){
		List<Room> rooms = roomservice.selectByProjectIdToCh(op.getPid());
		
		List<Room> roomcs = new ArrayList<Room>();
		for(int n=0;n<10;n++){
			if((num-1)*10+n<rooms.size()){
				roomcs.add(rooms.get((num-1)*10+n));
			}
		}
		
		Project project = projectservice.selectByPrimaryKey(op.getPid());
		model.addAttribute("project", project);
		model.addAttribute("roomcs", roomcs);
		model.addAttribute("op", op);
		model.addAttribute("num", num);
		model.addAttribute("size", rooms.size());
		
		if(rooms.size()%10 > 0){
			model.addAttribute("zongye",rooms.size()/10+1 );
		}else{
			model.addAttribute("zongye",rooms.size()/10 );
		}
		
		return "openingreport/add2";
    }
	
	@RequestMapping("add3")
    public String add3(Openingreport op,Integer num, Model model){
		List<Room> rooms = roomservice.selectByProjectIdToCh(op.getPid());
		
		List<Room> roomcs = new ArrayList<Room>();
		for(int n=0;n<10;n++){
			if((num-1)*10+n<rooms.size()){
				roomcs.add(rooms.get((num-1)*10+n));
			}
		}
		
		Project project = projectservice.selectByPrimaryKey(op.getPid());
		model.addAttribute("project", project);
		model.addAttribute("roomcs", roomcs);
		model.addAttribute("op", op);
		model.addAttribute("num", num);
		model.addAttribute("size", rooms.size());
		
		if(rooms.size()%10 > 0){
			model.addAttribute("zongye",rooms.size()/10+1 );
		}else{
			model.addAttribute("zongye",rooms.size()/10 );
		}
		
		return "openingreport/add3";
    }
	
	
	@RequestMapping("add2_1")
    public String add2_1(Integer pid,Integer yeshu,Model model){
		
		List<Complex> complexs = complexservice.selectByProjectId(pid);
		List<Room> room = roomservice.selectByProjectId(pid);
		List<Room> rooms = new ArrayList<Room>();
		for(int n=0;n<10;n++){
			if((yeshu-1)*10+n<room.size()){
			rooms.add(room.get((yeshu-1)*10+n));
			}
		}
		model.addAttribute("complexs", complexs);
		model.addAttribute("pid", pid);
		model.addAttribute("yeshu", yeshu);
		model.addAttribute("size", room.size());
		model.addAttribute("rooms", rooms);
		
		if(room.size()%10 > 0){
			model.addAttribute("zongye",room.size()/10+1 );
		}else{
			model.addAttribute("zongye",room.size()/10 );
		}
		
		
		return "openingreport/add2_1";
    }
	
	@RequestMapping("xiazai")
    public void xiazai(Integer pid,HttpServletRequest request,HttpServletResponse response) throws IOException{
		List<Room> list = roomservice.selectByProjectIdToCh(pid);
		request.getSession().setAttribute("roomss", list);
		response.setHeader("Content-Disposition","attachment;filename=jiage.xls");//指定下载的文件名  
	    response.setContentType("application/vnd.ms-excel");  
		 Export  ex = new Export();   
		 ex.buildBaojiaExcel(list, "价格表.xls",response.getOutputStream());
    }
	
	@RequestMapping("shangchuan")
    public String shangchuan(Openingreport op,Integer num, Model model,HttpServletRequest request) throws IOException {
		MultipartHttpServletRequest mv = (MultipartHttpServletRequest)request;
		MultipartFile cf = mv.getFile("file");
		String suffix1 = cf.getOriginalFilename().substring(cf.getOriginalFilename().lastIndexOf("."));
		if(suffix1.equals(".xls")){
			
			byte[] fb = cf.getBytes();
			String fileName = "";
			//设置时间戳格式
			SimpleDateFormat af = new SimpleDateFormat("yyyyMMddhhmmssSSS");
			//获得时间戳的字符串
			//Long timeStamp = System.currentTimeMillis();
			fileName = af.format(new Date());
			//加三位随机数 防止上面的时间戳可能出现的重复
			Random random = new Random();
			for(int i = 0; i < 3; i++){
				fileName = fileName + random.nextInt(10);
			}
			
			//原始文件名
			String oriFileName = cf.getOriginalFilename();
					
			//获取后缀名 包含.  .doc  .jsp  .exe
			String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));

			//获取路径
			String path = request.getSession().getServletContext().getRealPath("/");
			System.out.println("path-->"+path);
			String namenew = path+"/upload/"+fileName+ suffix;
			OutputStream out = new FileOutputStream(new File(path+"/upload/"+fileName+ suffix));
			out.write(fb);
			out.flush();
			out.close();
			
			InputStream is = new FileInputStream(namenew);
			HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
	        Room room = null;
	        List<Room> list = new ArrayList<Room>();
	          // 循环工作表Sheet
	        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
	             HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
	             if (hssfSheet == null) {
	                  continue;
	             }
	             // 循环行Row
	              for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
	                  HSSFRow hssfRow = hssfSheet.getRow(rowNum);
	                  if (hssfRow != null) {
	                      room = new Room();
	                      hssfRow.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
	                      hssfRow.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
	                      hssfRow.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
	                      hssfRow.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
	                      hssfRow.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
	                      room.setId(Integer.parseInt(hssfRow.getCell(0).getStringCellValue()));
	                      room.setRoomnumber(hssfRow.getCell(1).getStringCellValue());
	                      room.setArea(new Float(hssfRow.getCell(2).getStringCellValue()));
	                      room.setRoomprice(new Float(hssfRow.getCell(3).getStringCellValue()));
	                      room.setRoomtotal(new Float(hssfRow.getCell(4).getStringCellValue()));
	                     list.add(room);
	                 }
	              }
	        }
	       for (Room r : list) {
	    	   System.out.println(r.getId()+"--"+r.getRoomnumber()+"--"+r.getArea()+"--"+r.getRoomprice()+"--"+r.getRoomtotal());
	    	   roomservice.updateByPrimaryKeySelective(r);
	       }
		}
		else{
			System.out.println("文件类型错误！");
		}
		
		List<Room> rooms = roomservice.selectByProjectIdToCh(op.getPid());
		
		List<Room> roomcs = new ArrayList<Room>();
		for(int n=0;n<10;n++){
			if((num-1)*10+n<rooms.size()){
				roomcs.add(rooms.get((num-1)*10+n));
			}
		}
		
		Project project = projectservice.selectByPrimaryKey(op.getPid());
		model.addAttribute("project", project);
		model.addAttribute("roomcs", roomcs);
		model.addAttribute("op", op);
		model.addAttribute("num", num);
		model.addAttribute("size", rooms.size());
			if(rooms.size()%10 > 0){
			model.addAttribute("zongye",rooms.size()/10+1 );
		}else{
			model.addAttribute("zongye",rooms.size()/10 );
		}
		return "openingreport/add3";
	}
	
	@RequestMapping("add4")
    public String add4(Openingreport op,Model model){
		model.addAttribute("op", op);
		return "openingreport/add4";
    }
	@RequestMapping("add5")
    public String add5(Openingreport op,Model model){
		Project project = projectservice.selectByPrimaryKey(op.getPid());
		String pname = project.getName();
		model.addAttribute("pname", pname);
		model.addAttribute("op", op);
		return "openingreport/add5";
    }
	
	@RequestMapping("insert")
	 public String insert(Openingreport op,Model model){
		Map<String, Object> map = new HashMap<String,Object>();
		openingreportservice.insert(op);
		Integer opid = openingreportservice.selectMax();
		int pid = op.getPid();
		map.put("opid", opid);
		map.put("pid", pid);
		ophservice.insertroom(map);
		return "redirect:toList.do";
    }
	@RequestMapping("selectOne")
	 public String selectOne(Integer id,Model model){
		Openingreport op = openingreportservice.selectOne(id);
		model.addAttribute("op", op);
		Project project = projectservice.selectByPrimaryKey(op.getPid());
		String pname = project.getName();
		model.addAttribute("pname", pname);
		return "openingreport/one";
   }
	
	@RequestMapping("shenhe")
	 public String shenhe(Integer id,Integer pid,Model model){
		Openingreport op = new Openingreport();
		op.setId(id);
		op.setState("已审核");
		openingreportservice.update(op);
		roomservice.updateToOpen(id);
		return "redirect:toShenhe1.do";
   }
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
}
